package org.example.gui.listener;

import org.example.dao.BudgetDAO;
import org.example.gui.panel.ConfigPanel;
import org.example.util.DateUtil;
import org.example.util.GUIUtil;
import org.example.util.SQLUtil;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * ConfigPanel 的监听器，监听按钮后进行预算的改操作 和 调用工具类进行重置操作
 */

public class ConfigListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {
        ConfigPanel panel = ConfigPanel.instance;

        if (panel.bSubmit == e.getSource()) {
            if (GUIUtil.isEmpty(panel.tfBudget, "本月预算")) {
                return;
            }
            // 设置所有月预算
            String budgetName = BudgetDAO.budget + (panel.cbBudgetPerMonth.getSelectedIndex() + 1);
            BudgetDAO.update(budgetName, panel.tfBudget.getText());

            // 设置当月预算
            String thisMonthBudget = BudgetDAO.getValueByKey(BudgetDAO.budget + (DateUtil.thisMonth() + 1));
            BudgetDAO.update(BudgetDAO.budget, thisMonthBudget);

            JOptionPane.showMessageDialog(panel, "设置成功");
        }

        if (panel.bTruncate == e.getSource()) {
            if (JOptionPane.OK_OPTION != JOptionPane.showConfirmDialog(panel, "确实清空所有数据？")) {
                return;
            }
            SQLUtil.truncate();
            //重新初始化数据库
            BudgetDAO.init();
            JOptionPane.showMessageDialog(panel, "重置成功");
        }
    }
}
